package com.fjzcit.io.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author Atu
 * @Date 2024/6/22 17:55
 * @Version 1.0
 */
public class SocketBIO {
    public static void main(String[] args) throws IOException {
        System.out.println("Before Listening for port 9999 ...");
        // 暂停 1
        System.in.read();
        ServerSocket server = new ServerSocket(9999);
        System.out.println("Step1: new ServerSocket(9999)");
        // 暂停 2
        System.in.read();
        while (true) {
            System.out.println("Before Accepting Connection ...");
            // 暂停 3
            System.in.read();
            // 阻塞 1
            final Socket client = server.accept();
            System.out.println("Step2: Client\t" + client.getPort());
            // 暂停 4
            System.in.read();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    InputStream in = null;
                    try {
                        in = client.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                        while(true) {
                            // 阻塞 2
                            String dataLine = reader.readLine();
                            if(!"exit".equals(dataLine)) {
                                System.out.println(dataLine);
                            } else {
                                client.close();
                                break;
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
